/**
 * 
 */
package elitech.vietnam.weatherfashion.tabs.styler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.backgroundtask.ButtonAskFriendTask;
import elitech.vietnam.weatherfashion.backgroundtask.PostCommentTask;
import elitech.vietnam.weatherfashion.backgroundtask.PostLikeTask;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.custom.CommentAdapter;
import elitech.vietnam.weatherfashion.custom.LikeButton;
import elitech.vietnam.weatherfashion.custom.dialogues.DialogUserInfo;
import elitech.vietnam.weatherfashion.custom.dialogues.EditPostDialog;
import elitech.vietnam.weatherfashion.custom.dialogues.TimeOutDialog;
import elitech.vietnam.weatherfashion.dto.CommentDTO;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.tabs.AbstractFragment;
import elitech.vietnam.weatherfashion.tabs.BaseContainerFragment;
import elitech.vietnam.weatherfashion.tabs.zoompager.ZoomPagerItemFragment;
import elitech.vietnam.weatherfashion.ultilities.MyDialogHandler;

/**
 * @author Cong
 * 
 */
public class StylerPostFragment extends AbstractFragment implements View.OnClickListener {

	private PostDTO post;
	private MemberDTO member;
	private List<CommentDTO> comments;
	private ImageView image_useravatar, image_main, image_addfriend;
	private TextView text_username, text_commentcount, text_userstatus, text_content, text_p_commentcount;
	private LinearLayout layout_comments;
	private ProgressBar progress_addfriend;
	private Button button_comment, /* button_camera, */button_editpost;
	private LikeButton button_like;
	private EditText textbox_comment;

	private CommentAdapter mCAdapter;

	public static StylerPostFragment init(PostDTO post, MemberDTO member) {
		StylerPostFragment frm = new StylerPostFragment();
		frm.post = post;
		frm.member = member;
		return frm;
	}
	public static StylerPostFragment init(PostDTO post) {
		StylerPostFragment frm = new StylerPostFragment();
		frm.post = post;
		return frm;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.tab_stylerpostdetail, container, false);
		setupView(view);

		image_useravatar = (ImageView) view.findViewById(R.id.meminfo_image_useravatar);
		text_username = (TextView) view.findViewById(R.id.meminfo_textview_username);
		text_userstatus = (TextView) view.findViewById(R.id.meminfo_textview_userstatus);
		image_main = (ImageView) view.findViewById(R.id.stylerpost_imageview_main);
		text_commentcount = (TextView) view.findViewById(R.id.stylerpost_textview_commentcount);
		layout_comments = (LinearLayout) view.findViewById(R.id.stylerpost_layout_comments);
		progress_addfriend = (ProgressBar) view.findViewById(R.id.meminfo_addfriend_progress);
		image_addfriend = (ImageView) view.findViewById(R.id.meminfo_button_addfriend);
		text_content = (TextView) view.findViewById(R.id.stylerpost_textview_content);
		button_like = (LikeButton) view.findViewById(R.id.stylerpost_button_like);
		button_comment = (Button) view.findViewById(R.id.stylerpost_button_sendcomment);
		textbox_comment = (EditText) view.findViewById(R.id.stylerpost_textbox_comment);
		text_p_commentcount = (TextView) view.findViewById(R.id.meminfo_textview_commentcount);
		// button_camera = (Button)
		// view.findViewById(R.id.styler_button_camera);
		button_editpost = (Button) view.findViewById(R.id.meminfo_button_edit);

		if (!isAdded())
			return null;

		if (post == null) {
			onNoData(true);
			return view;
		}

		button_like.setUp(true);
		button_like.setOnClickListener(this);
		button_comment.setOnClickListener(this);
		
		if (member == null)
			new GetMemberTask().execute();
		else
			loadMember();
		
		new GetCommentTask().execute();

		loadPost();
		loadButtonFriend();

		// button_camera.setOnClickListener(this);

		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (getActivity().getIntent().getIntExtra("POST_RELOAD", -1) > 0) {
			getActivity().getIntent().removeExtra("POST_RELOAD");
			getActivity().onBackPressed();
		}
	}

	public void loadMember() {
		if (member == null)
			return;
		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// this.member.getMemberPic(), image_useravatar);
		UrlImageViewHelper.setUrlDrawable(image_useravatar, Const.SERVER_IMAGE_URL + this.member.getMemberPic(), R.drawable.no_avatar);
		this.text_username.setText(this.member.getMemberName());
		this.text_userstatus.setText(this.member.getMemberProfile());
		loadButtonFriend();
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (user != null && (post.getStoreId() == user.getId())) {
			button_editpost.setVisibility(View.VISIBLE);
			button_editpost.setOnClickListener(this);
		}
		image_useravatar.setOnClickListener(this);
	}

	public void loadPost() {
		text_content.setText(post.getContent());
		// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL +
		// this.post.getImage(), image_main);
		UrlImageViewHelper.setUrlDrawable(image_main, Const.SERVER_IMAGE_URL + this.post.getImage(), R.drawable.loading_time);
		button_like.setData(post.getLikes(), post.isLiked());
		image_main.setOnClickListener(this);
	}

	public void loadComments() {
		this.text_commentcount.setText("");
		if (this.comments == null)
			this.comments = new ArrayList<CommentDTO>();
		mCAdapter = new CommentAdapter(getActivity(), R.layout.layout_comment, comments);
		mCAdapter.LoadList(layout_comments);
		this.text_commentcount.setText(this.comments.size() + getString(R.string._comments));
		this.text_p_commentcount.setText(String.valueOf(this.comments.size()));
		this.text_p_commentcount.setVisibility(View.VISIBLE);
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(textbox_comment.getWindowToken(), 0);

		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		switch (v.getId()) {
		case R.id.stylerpost_button_like:
			button_like.setEnabled(false);
			if (user == null) {
				Utils.openLogin(getActivity());
			} else {
				String ms = getString(R.string.do_you_want_to_like_this_post_);
				if (post.isLiked())
					ms = getString(R.string.do_you_want_to_unlike_this_post_);
				new MyDialogHandler().confirm(getActivity(), getString(R.string.like_confirm), ms, getString(R.string.no), getString(R.string.yes), new Runnable() {
					@Override
					public void run() {
						new PostLikeTask(getActivity(), button_like, post, !post.isLiked()).execute();
						// liked = !liked;
					}
				}, null);
			}
			button_like.setEnabled(true);
			break;

		case R.id.stylerpost_button_sendcomment:
			if (user == null) {
				Utils.openLogin(getActivity());
			} else if (!this.textbox_comment.getText().toString().trim().equals("")) {
				if (user.getId() != this.post.getStoreId())
					new PostCommentTask(getActivity(), this.post, mCAdapter, layout_comments, text_commentcount, text_p_commentcount).execute(this.textbox_comment.getText().toString(), "addNotification");
				else
					new PostCommentTask(getActivity(), this.post, mCAdapter, layout_comments, text_commentcount, text_p_commentcount).execute(this.textbox_comment.getText().toString());
				this.textbox_comment.setText("");
			}
			break;

		case R.id.meminfo_button_addfriend:
			new ButtonAskFriendTask(getActivity(), image_addfriend, progress_addfriend).execute(user.getId(), member.getId());
			break;
		//
		// case R.id.styler_button_camera:
		// if (!AppConfig.getInstance().isLoggedIn ||
		// AppConfig.getInstance().appUser == null) {
		// Intent intent = new Intent(getActivity(), LoginActivity.class);
		// startActivity(intent);
		// } else
		// new PicPickerDialog(getActivity(), this).show();
		// break;
		//
		case R.id.stylerpost_imageview_main:
			((BaseContainerFragment) getParentFragment()).replaceFragment(ZoomPagerItemFragment.init(Const.SERVER_IMAGE_URL + post.getImage()), true);
			break;

		case R.id.meminfo_button_edit:
			new EditPostDialog(getActivity(), post, user.getId()).show();
			break;

		case R.id.meminfo_image_useravatar:
			new DialogUserInfo(getActivity(), member).show();
			break;

		default:
			break;
		}
	}

	public void loadButtonFriend() {
		MemberDTO user = GlobalValue.getInstance(getActivity()).readUserInfo();
		if (member == null || WFApplication.getInstance().userFriends == null || user == null)
			return;
		if (member.getId() == user.getId())
			return;
		if (Utils.isFriend(member.getId())) {
			image_addfriend.setImageResource(R.drawable.icon_friended);
		} else {
			image_addfriend.setImageResource(R.drawable.icon_addfriend);
			image_addfriend.setOnClickListener(this);
		}
	}

	//
	// class StylerPostLoadingTask extends AsyncTask<Integer, Integer, String> {
	// @Override
	// protected String doInBackground(Integer... params) {
	// AppUtils.Log("Styler Post Loading...");
	// PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
	// comments = appService.getListComment(post.getId());
	// if (AppConfig.getInstance().isLoggedIn && AppConfig.getInstance().appUser
	// != null)
	// liked = appService.isLiked(AppConfig.getInstance().appUser.getId(),
	// post.getId());
	// return null;
	// }
	// @Override
	// protected void onPreExecute() {
	// super.onPreExecute();
	// }
	// @Override
	// protected void onPostExecute(String result) {
	// super.onPostExecute(result);
	// if (!isAdded())
	// return;
	// loadComments();
	// button_like.setData(post.getLikes(), liked);
	// }
	// }
	//
	class GetCommentTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			try {
				comments = appService.getListComment(post.getId());
			} catch (IOException e) {
				return false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			loadComments();
		}
	}
	
	class GetMemberTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			try {
				member = appService.getInfoMember(post.getStoreId());
			} catch (IOException e) {
				return false;
			}
			return null;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (!isAdded())
				return;
			if (result != null) {
				new TimeOutDialog(getActivity()).show();
				return;
			}
			loadMember();
		}
	}

	//
	// class GetLikedTask extends AsyncTask<Integer, Integer, Boolean> {
	// @Override
	// protected Boolean doInBackground(Integer... params) {
	// PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
	// liked = appService.isLiked(AppConfig.getInstance().appUser.getId(),
	// post.getId());
	// return null;
	// }
	// @Override
	// protected void onPostExecute(Boolean result) {
	// super.onPostExecute(result);
	// if (!isAdded())
	// return;
	// button_like.setData(post.getLikes(), liked);
	// }
	// }

	class DeletePostTask extends AsyncTask<Integer, Integer, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {

			return null;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getActivity(), "Post deleted successfully.", Toast.LENGTH_LONG).show();
				getFragmentManager().popBackStack();
			} else
				Toast.makeText(getActivity(), "Error deleting post. Please try again later.", Toast.LENGTH_LONG).show();
		}
	}
}
